<template>
  <div class="repayment-analysis">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>还款统计分析</h3>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <el-form :model="filterForm" inline class="filter-form">
        <el-form-item label="统计周期">
          <el-select v-model="filterForm.period" placeholder="请选择统计周期" @change="handlePeriodChange">
            <el-option label="日" value="day"></el-option>
            <el-option label="周" value="week"></el-option>
            <el-option label="月" value="month"></el-option>
            <el-option label="季" value="quarter"></el-option>
            <el-option label="年" value="year"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            :type="datePickerType"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="产品类型">
          <el-select v-model="filterForm.productType" placeholder="请选择产品类型" clearable @change="handleFilterChange">
            <el-option label="个人贷款" value="personal"></el-option>
            <el-option label="企业贷款" value="business"></el-option>
            <el-option label="消费贷款" value="consumer"></el-option>
            <el-option label="房屋贷款" value="mortgage"></el-option>
            <el-option label="车辆贷款" value="car"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-title">应还总额</div>
            <div class="stat-value">{{ formatCurrency(statistics.totalDueAmount) }}</div>
            <div class="stat-compare" :class="statistics.totalDueAmountCompare > 0 ? 'up' : 'down'">
              <el-icon><component :is="statistics.totalDueAmountCompare > 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              {{ Math.abs(statistics.totalDueAmountCompare) }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-title">实还总额</div>
            <div class="stat-value">{{ formatCurrency(statistics.totalPaidAmount) }}</div>
            <div class="stat-compare" :class="statistics.totalPaidAmountCompare > 0 ? 'up' : 'down'">
              <el-icon><component :is="statistics.totalPaidAmountCompare > 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              {{ Math.abs(statistics.totalPaidAmountCompare) }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-title">回收率</div>
            <div class="stat-value">{{ statistics.recoveryRate }}%</div>
            <div class="stat-compare" :class="statistics.recoveryRateCompare > 0 ? 'up' : 'down'">
              <el-icon><component :is="statistics.recoveryRateCompare > 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              {{ Math.abs(statistics.recoveryRateCompare) }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-title">逾期率</div>
            <div class="stat-value">{{ statistics.overdueRate }}%</div>
            <div class="stat-compare" :class="statistics.overdueRateCompare < 0 ? 'up' : 'down'">
              <el-icon><component :is="statistics.overdueRateCompare < 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
              {{ Math.abs(statistics.overdueRateCompare) }}%
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>还款趋势</span>
                <el-radio-group v-model="trendChartType" size="small" @change="handleTrendTypeChange">
                  <el-radio-button label="amount">金额</el-radio-button>
                  <el-radio-button label="count">笔数</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" ref="trendChartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>还款方式分布</span>
                <el-radio-group v-model="payMethodChartType" size="small" @change="handlePayMethodTypeChange">
                  <el-radio-button label="amount">金额</el-radio-button>
                  <el-radio-button label="count">笔数</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" ref="payMethodChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>逾期情况分析</span>
              </div>
            </template>
            <div class="chart-container" ref="overdueChartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>产品类型还款分布</span>
              </div>
            </template>
            <div class="chart-container" ref="productChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 还款排行榜 -->
      <el-card shadow="hover" class="ranking-card">
        <template #header>
          <div class="chart-header">
            <span>还款排行榜</span>
            <el-tabs v-model="rankingType" @tab-change="handleRankingTypeChange">
              <el-tab-pane label="客户还款排行" name="customer"></el-tab-pane>
              <el-tab-pane label="产品还款排行" name="product"></el-tab-pane>
            </el-tabs>
          </div>
        </template>
        <el-table :data="rankingData" border style="width: 100%">
          <el-table-column type="index" label="排名" width="80"></el-table-column>
          <el-table-column :prop="rankingType === 'customer' ? 'customerName' : 'productName'" :label="rankingType === 'customer' ? '客户名称' : '产品名称'" width="180"></el-table-column>
          <el-table-column prop="totalAmount" label="还款总额" width="150">
            <template #default="scope">
              {{ formatCurrency(scope.row.totalAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="count" label="还款笔数" width="120"></el-table-column>
          <el-table-column prop="onTimeRate" label="按时还款率" width="120">
            <template #default="scope">
              {{ scope.row.onTimeRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="avgAmount" label="平均还款金额" width="150">
            <template #default="scope">
              {{ formatCurrency(scope.row.avgAmount) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { repaymentStatisticsApi, overdueApi } from '@/api/repayment'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer
])

// 统计数据
const statistics = reactive({
  totalDueAmount: 0,
  totalPaidAmount: 0,
  recoveryRate: 0,
  overdueRate: 0,
  totalDueAmountCompare: 0,
  totalPaidAmountCompare: 0,
  recoveryRateCompare: 0,
  overdueRateCompare: 0
})

// 筛选表单
const filterForm = reactive({
  period: 'month',
  dateRange: [
    new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1).toISOString().split('T')[0],
    new Date().toISOString().split('T')[0]
  ],
  productType: ''
})

// 日期选择器类型
const datePickerType = ref('daterange')

// 图表类型
const trendChartType = ref('amount')
const payMethodChartType = ref('amount')

// 排行榜类型
const rankingType = ref('customer')

// 图表实例引用
const trendChartRef = ref(null)
const payMethodChartRef = ref(null)
const overdueChartRef = ref(null)
const productChartRef = ref(null)

// 图表实例
let trendChart = null
let payMethodChart = null
let overdueChart = null
let productChart = null

// 排行榜数据
const rankingData = ref([])

// 初始化
onMounted(() => {
  initCharts()
  fetchData()
})

// 初始化图表
const initCharts = () => {
  // 初始化还款趋势图表
  trendChart = echarts.init(trendChartRef.value)
  
  // 初始化还款方式分布图表
  payMethodChart = echarts.init(payMethodChartRef.value)
  
  // 初始化逾期情况图表
  overdueChart = echarts.init(overdueChartRef.value)
  
  // 初始化产品类型图表
  productChart = echarts.init(productChartRef.value)
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    trendChart.resize()
    payMethodChart.resize()
    overdueChart.resize()
    productChart.resize()
  })
}

// 获取数据
const fetchData = () => {
  fetchStatisticsData()
  fetchOverdueData()
}

// 获取还款统计数据
const fetchStatisticsData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1],
    type: filterForm.period
  }
  
  repaymentStatisticsApi.getStatistics(params).then(res => {
    // 更新统计卡片数据
    statistics.totalDueAmount = res.data.totalRepayAmount
    statistics.totalPaidAmount = res.data.totalPrincipal + res.data.totalInterest + res.data.totalPenalty
    statistics.recoveryRate = ((statistics.totalPaidAmount / statistics.totalDueAmount) * 100).toFixed(2)
    
    // 更新趋势图表
    updateTrendChart(res.data.details)
    
    // 更新还款方式分布图表（示例数据，实际应通过API获取）
    updatePayMethodChart()
    
    // 更新产品类型分布图表（示例数据，实际应通过API获取）
    updateProductChart()
  })
}

// 获取逾期统计数据
const fetchOverdueData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  overdueApi.getOverdueStatistics(params).then(res => {
    // 更新逾期率
    statistics.overdueRate = parseFloat(res.data.overdueRate)
    
    // 更新逾期情况图表
    updateOverdueChart(res.data)
  })
}

// 更新趋势图表
const updateTrendChart = (data) => {
  const xData = data.map(item => item.date)
  const yData = trendChartType.value === 'amount' 
    ? data.map(item => item.repayAmount)
    : data.map(item => item.count)
  
  const option = {
    title: {
      text: '还款趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        return `${params[0].name}<br/>
                ${params[0].seriesName}: ${formatCurrency(params[0].value)}<br/>
                ${params[1].seriesName}: ${formatCurrency(params[1].value)}<br/>
                ${params[2].seriesName}: ${formatCurrency(params[2].value)}`
      }
    },
    legend: {
      data: ['总额', '本金', '利息'],
      bottom: 10
    },
    xAxis: {
      type: 'category',
      data: xData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function(value) {
          return formatCurrency(value)
        }
      }
    },
    series: [
      {
        name: '总额',
        type: 'bar',
        data: data.map(item => trendChartType.value === 'amount' ? item.repayAmount : item.count),
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '本金',
        type: 'line',
        data: data.map(item => trendChartType.value === 'amount' ? item.principal : 0),
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '利息',
        type: 'line',
        data: data.map(item => trendChartType.value === 'amount' ? item.interest : 0),
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 更新还款方式分布图表
const updatePayMethodChart = () => {
  // 示例数据，实际应通过API获取
  const data = [
    { name: '银行转账', value: 65, count: 120 },
    { name: '现金', value: 15, count: 30 },
    { name: '支付宝', value: 12, count: 25 },
    { name: '微信', value: 8, count: 15 }
  ]
  
  const option = {
    title: {
      text: '还款方式分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: data.map(item => item.name)
    },
    series: [
      {
        name: payMethodChartType.value === 'amount' ? '金额占比' : '笔数占比',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map(item => ({
          name: item.name,
          value: payMethodChartType.value === 'amount' ? item.value : item.count
        }))
      }
    ]
  }
  
  payMethodChart.setOption(option)
}

// 更新逾期情况图表
const updateOverdueChart = (data) => {
  // 构建逾期图表数据
  const daysData = [
    { name: '1-30天', value: data.overdueDaysDistribution['1-30'] },
    { name: '31-60天', value: data.overdueDaysDistribution['31-60'] },
    { name: '61-90天', value: data.overdueDaysDistribution['61-90'] },
    { name: '90天以上', value: data.overdueDaysDistribution['90+'] }
  ]
  
  const statusData = [
    { name: '未处理', value: data.statusDistribution.pending },
    { name: '已提醒', value: data.statusDistribution.reminded },
    { name: '已催收', value: data.statusDistribution.collected },
    { name: '已结清', value: data.statusDistribution.settled }
  ]
  
  const option = {
    title: {
      text: '逾期情况分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      data: ['逾期天数', '处理状态'],
      bottom: 10
    },
    series: [
      {
        name: '逾期天数',
        type: 'pie',
        radius: [0, '30%'],
        label: {
          position: 'inner',
          fontSize: 14
        },
        data: daysData
      },
      {
        name: '处理状态',
        type: 'pie',
        radius: ['45%', '60%'],
        labelLine: {
          length: 30
        },
        label: {
          formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
          backgroundColor: '#F6F8FC',
          borderColor: '#8C8D8E',
          borderWidth: 1,
          borderRadius: 4,
          rich: {
            a: {
              color: '#6E7079',
              lineHeight: 22,
              align: 'center'
            },
            hr: {
              borderColor: '#8C8D8E',
              width: '100%',
              borderWidth: 1,
              height: 0
            },
            b: {
              color: '#4C5058',
              fontSize: 14,
              fontWeight: 'bold',
              lineHeight: 33
            },
            per: {
              color: '#fff',
              backgroundColor: '#4C5058',
              padding: [3, 4],
              borderRadius: 4
            }
          }
        },
        data: statusData
      }
    ]
  }
  
  overdueChart.setOption(option)
}

// 更新产品类型分布图表
const updateProductChart = () => {
  // 示例数据，实际应通过API获取
  const data = [
    { name: '个人贷款', value: 45 },
    { name: '企业贷款', value: 25 },
    { name: '消费贷款', value: 15 },
    { name: '房屋贷款', value: 10 },
    { name: '车辆贷款', value: 5 }
  ]
  
  const option = {
    title: {
      text: '产品类型还款分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '产品类型',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  productChart.setOption(option)
}

// 还款趋势图表类型变更
const handleTrendTypeChange = () => {
  fetchStatisticsData()
}

// 还款方式图表类型变更
const handlePayMethodTypeChange = () => {
  updatePayMethodChart()
}

// 筛选条件变更
const handleFilterChange = () => {
  fetchData()
}

// 周期变更
const handlePeriodChange = () => {
  switch (filterForm.period) {
    case 'day':
      datePickerType.value = 'daterange'
      break
    case 'week':
      datePickerType.value = 'daterange'
      break
    case 'month':
      datePickerType.value = 'monthrange'
      break
    case 'quarter':
      datePickerType.value = 'monthrange'
      break
    case 'year':
      datePickerType.value = 'yearrange'
      break
  }
  
  fetchData()
}

// 日期变更
const handleDateChange = () => {
  fetchData()
}

// 刷新数据
const refreshData = () => {
  fetchData()
}

// 导出
const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

// 排行榜类型变更
const handleRankingTypeChange = () => {
  // 实际应根据类型获取不同的排行榜数据
}

// 格式化金额
const formatCurrency = (amount) => {
  if (!amount && amount !== 0) return '¥0.00'
  return '¥' + parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
</script>

<style scoped>
.repayment-analysis {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 10px;
}

.stat-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.stat-compare {
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-compare.up {
  color: #67C23A;
}

.stat-compare.down {
  color: #F56C6C;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.ranking-card {
  margin-bottom: 20px;
}
</style> 